package com.bestv.engine.filter;

import com.bestv.database.dao.DaoFactory;
import com.bestv.database.vo.Program;
import com.bestv.engine.model.RecommendationItem;
import org.apache.commons.lang3.StringUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by elena on 15-5-20.
 */
public class MovieFilter implements Filter {
    private String prefix = "Umai";
    private String biz;
    private Pattern pattern;
    private Integer itemVersion = 1;
    private Integer hdsdType = 1;

    public MovieFilter(String programIdRaw, String biz, String ruleFormat) {
        this.biz = biz;
        if (StringUtils.isNotBlank(biz)) {
            pattern = Pattern.compile(biz);
        }
        if (StringUtils.isNotBlank(programIdRaw)) {
            prefix = programIdRaw.split("[:_]")[0];
            if (!"Umai".equals(prefix) && !"movie".equals(prefix)) prefix = "Umai";
        } else if ("json".equals(ruleFormat)) {
            prefix = "movie";
        }
        if (StringUtils.isNotBlank(programIdRaw) && "Umai".equals(prefix)) {
            Program program = DaoFactory.getProgramDao().findByMediaCode(programIdRaw);
            if (program != null && program.getSeriesCode().startsWith("movie") && program.getHdsdType() <= 2) {
                itemVersion = program.getItemVersion();
                hdsdType = program.getHdsdType();
            }
        }
    }

    @Override
    public boolean accept(RecommendationItem item) {
        if (item.getTypeId() != 2) return true;

        String seriesCode = item.getItemId();
        if (seriesCode.startsWith("Umai")) return "Umai".equals(prefix);

        if (seriesCode.startsWith("movie") && "Umai".equals(prefix)) {
            Program program = DaoFactory.getProgramDao().findBySeriesCode(seriesCode, itemVersion, hdsdType);
            if (program != null) {
                item.setItemId(program.getMediaCode());
                item.setName(program.getName());
                return true;
            } else {
                return false;
            }
        }

        if (seriesCode.startsWith("movie") && "movie".equals(prefix)) {
            String domain = item.getDomain();
            if (StringUtils.isNotBlank(biz)) {
                item.setBiz(biz);
                Matcher m = pattern.matcher(domain);
                if (m.find()) {
                    String category = domain.substring(m.end() + 1, domain.indexOf(";", m.start()));
                    item.setCategory(category);
                    return true;
                } else {
                    return false;
                }
            } else {
                domain = domain.substring(0, domain.indexOf(";"));
                item.setBiz(domain.split(":")[0]);
                item.setCategory(domain.split(":")[1]);
                return true;
            }
        }
        return false;
    }
}
